package week10;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author The setting sun
 * @version 1.0
 * @title: Work4
 * @description: TODO
 * @date 2021/11/11 14:53
 */
public class Work4 {
    public static void main(String[] args) {
        new MyFrame1().Init();
    }
}

class MyFrame1 {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    class Ball extends Thread {
        int x;
        int y;
        Graphics g;

        public Ball(int x, int y, Graphics g) {
            this.x = x;
            this.y = y;
            this.g = g;
        }

        @Override
        public void run() {
            int r = (int) (Math.random() * 16 + 5);
            int dx = (int) (Math.random() * 20 + 1);
            int dy = -(int) (Math.random() * 20 + 1);

            int zf = (int) (Math.random() * 2 + 1);

            switch (zf) {
                case 1:
                    dx = dx;
                    break;
                case 2:
                    dx = -dx;
                    break;
            }

            switch (zf) {
                case 1:
                    dy = dy;
                    break;
                case 2:
                    dy = -dy;
                    break;
            }

            Boolean first = true;

            int R = (int) (Math.random() * 256);
            int G = (int) (Math.random() * 256);
            int B = (int) (Math.random() * 256);
            g.setXORMode(new Color(R, G, B));

            while (true) {
                if (x < 0 || x >= 600) {
                    dx = -dx;
                }

                if (y < 0 || y >= 500) {
                    dy = -dy;
                }

                try {
                    sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (first == false) {
                    g.fillOval(x, y, r, r);
                }

                x = x + dx;
                y = y + dy;
                g.fillOval(x, y, r, r);

                first = false;
            }
        }
    }

    public void Init() {
        panel.setSize(600, 500);
        panel.setBackground(Color.PINK);

        frame.add(panel);

        frame.setVisible(true);
        frame.setSize(600, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                new Ball(e.getX(), e.getY(), panel.getGraphics()).start();
            }
        });
    }
}
